<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddUser">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索用户名/ID/邮箱" 
        prefix-icon="Search"
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-select v-model="statusFilter" placeholder="用户状态" class="filter-select">
        <el-option label="全部" value="" />
        <el-option label="正常" value="active" />
        <el-option label="禁用" value="disabled" />
        <el-option label="待审核" value="pending" />
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table 
      v-loading="loading" 
      :data="usersData" 
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="用户ID" width="100" sortable />
      <el-table-column prop="username" label="用户名" sortable>
        <template #default="scope">
          <div class="username-cell">
            <el-avatar :src="scope.row.avatar" class="user-avatar" />
            <span>{{ scope.row.username }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="role" label="角色" sortable>
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">{{ scope.row.role }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" sortable>
        <template #default="scope">
          <el-switch 
            v-model="scope.row.status" 
            :active-value="'active'" 
            :inactive-value="'disabled'"
            @change="handleStatusChange(scope.row.id, $event)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.lastLogin) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable>
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEditUser(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDeleteUser(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalUsers"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form 
        ref="userFormRef" 
        :model="userForm" 
        :rules="userRules" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" v-if="!editingUserId">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
            <el-option label="超级管理员" value="superadmin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch 
            v-model="userForm.status" 
            :active-value="'active'" 
            :inactive-value="'disabled'"
            active-text="启用" 
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'

// 表格数据
const users = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(0)
const selectedUsers = ref([])

// 搜索和筛选条件
const searchKeyword = ref('')
const statusFilter = ref('')

// 对话框相关
const dialogVisible = ref(false)
const editingUserId = ref(null)
const dialogTitle = computed(() => editingUserId.value ? '编辑用户' : '添加用户')
const userFormRef = ref(null)

// 用户表单数据
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  role: 'user',
  status: 'active'
})

// 表单验证规则
const userRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 根据角色获取标签类型
const getRoleTagType = (role) => {
  const roleMap = {
    'user': 'default',
    'admin': 'primary',
    'superadmin': 'success'
  }
  return roleMap[role] || 'default'
}

// 过滤后的用户数据
const usersData = computed(() => {
  let filtered = [...users.value]
  
  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(keyword) ||
      user.id.toString().includes(keyword) ||
      user.email.toLowerCase().includes(keyword)
    )
  }
  
  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }
  
  // 更新总数
  totalUsers.value = filtered.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 模拟加载用户数据
const loadUsersData = () => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    const mockUsers = Array.from({ length: 50 }, (_, i) => ({
      id: 10000 + i,
      username: `user${i + 1}`,
      email: `user${i + 1}@example.com`,
      avatar: `https://api.dicebear.com/9.x/avataaars/svg?seed=user${i + 1}`,
      role: i < 5 ? (i === 0 ? 'superadmin' : 'admin') : 'user',
      status: i < 45 ? 'active' : 'disabled',
      lastLogin: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      createTime: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    users.value = mockUsers
    loading.value = false
  }, 500)
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 选择用户变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 打开添加用户对话框
const handleAddUser = () => {
  editingUserId.value = null
  // 重置表单
  Object.assign(userForm, {
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
  })
  dialogVisible.value = true
}

// 打开编辑用户对话框
const handleEditUser = (user) => {
  editingUserId.value = user.id
  // 填充表单数据
  Object.assign(userForm, {
    username: user.username,
    email: user.email,
    role: user.role,
    status: user.status
  })
  dialogVisible.value = true
}

// 提交用户表单
const handleSubmitUser = async () => {
  try {
    // 验证表单
    await userFormRef.value.validate()
    
    loading.value = true
    
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (editingUserId.value) {
      // 编辑用户
      const index = users.value.findIndex(user => user.id === editingUserId.value)
      if (index !== -1) {
        users.value[index] = {
          ...users.value[index],
          username: userForm.username,
          email: userForm.email,
          role: userForm.role,
          status: userForm.status
        }
      }
      ElMessage.success('用户更新成功')
    } else {
      // 添加用户
      const newUser = {
        id: Date.now(),
        username: userForm.username,
        email: userForm.email,
        password: userForm.password,
        avatar: `https://api.dicebear.com/9.x/avataaars/svg?seed=${userForm.username}`,
        role: userForm.role,
        status: userForm.status,
        lastLogin: null,
        createTime: new Date().toISOString()
      }
      users.value.unshift(newUser)
      ElMessage.success('用户添加成功')
    }
    
    // 关闭对话框
    dialogVisible.value = false
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 删除用户
const handleDeleteUser = (userId) => {
  ElMessageBox.confirm(
    '确定要删除这个用户吗？此操作不可撤销。',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        const index = users.value.findIndex(user => user.id === userId)
        if (index !== -1) {
          users.value.splice(index, 1)
        }
        ElMessage.success('用户删除成功')
        loading.value = false
      }, 500)
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 修改用户状态
const handleStatusChange = (userId, newStatus) => {
  loading.value = true
  
  // 模拟API请求延迟
  setTimeout(() => {
    const user = users.value.find(u => u.id === userId)
    if (user) {
      user.status = newStatus
      ElMessage.success(`用户状态已更新为${newStatus === 'active' ? '启用' : '禁用'}`)
    }
    loading.value = false
  }, 300)
}

// 页面加载时初始化数据
onMounted(() => {
  loadUsersData()
})
</script>

<style scoped>
.user-management {
  width: 100%;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索和筛选区域 */
.search-filter-section {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

/* 用户名单元格样式 */
.username-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
}

/* 分页区域 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .search-input {
    width: 200px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .search-filter-section {
    flex-direction: column;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style>